<template>
  <el-dialog
    v-model="visible"
    class="component-coupon-add-or-update"
    :title="dataForm.couponId ? $t('coupon.viewCoupon') : $t('coupon.newCoupon')"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :disabled="true"
      :label-width="$t('language') === 'language' ? '170px':'100px'"

      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('coupon.couponName')"
        prop="couponName"
      >
        <el-input
          v-model="dataForm.couponName"
          :placeholder="$t('coupon.couponName')"
          :disabled="dataForm.couponId !== 0"
        />
      </el-form-item>
      <el-form-item
        :label="$t('coupon.deliveryStatus')"
        prop="putonStatus"
      >
        <el-radio-group v-model="dataForm.putonStatus">
          <el-radio :label="0">
            {{ $t("coupon.waitAutoLaunch") }}
            <el-tooltip
              class="item"
              effect="light"
              placement="top"
            >
              <template #content>
                <div>
                  {{ $t("coupon.launchTip") }}
                </div>
              </template>
              <span>
                <el-icon><QuestionFilled /></el-icon>
              </span>
            </el-tooltip>
          </el-radio>
          <el-radio :label="1">
            {{ $t("coupon.launched") }}
          </el-radio>
          <el-radio :label="4">
            {{ $t("coupon.waitLaunch") }}
          </el-radio>
          <el-radio :label="-1">
            {{ $t("coupon.cancelLaunch") }}
            <el-tooltip
              class="item"
              effect="light"
              placement="top"
            >
              <template #content>
                <div>
                  {{ $t("coupon.launchTip1") }}
                </div>
              </template>
              <span>
                <el-icon><QuestionFilled /></el-icon>
              </span>
            </el-tooltip>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="$t('coupon.getWay')"
        prop="getWay"
      >
        <el-radio-group v-model="dataForm.getWay">
          <el-radio :label="0">
            {{ $t("coupon.receiveDirectly") }}
          </el-radio>
          <el-radio :label="1">
            {{ $t("coupon.exchangeOrSystemIssue") }}
          </el-radio>
          <!-- <el-radio :label="3">兑换券</el-radio> -->
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="$t('coupon.couponType')"
        prop="couponType"
      >
        <el-radio-group
          v-model="dataForm.couponType"
          :disabled="dataForm.couponId !== 0"
        >
          <el-radio :label="1">
            {{ $t('coupon.cashCoupon') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('coupon.discountVoucher') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 投放时间 -->
      <el-form-item
        v-if="dataForm.putonStatus === 0"
        :label="$t('coupon.timeToMarket')"
        prop="launchTime"
      >
        <el-date-picker
          v-model="dataForm.launchTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetime"
          :placeholder="$t('coupon.chooseLaunchTime')"
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.couponType === 1"
        :label="$t('coupon.reductionAmount')"
        prop="reduceAmount"
      >
        <el-input
          v-model="dataForm.reduceAmount"
          :placeholder="$t('coupon.reductionAmount')"
          type="number"
          :disabled="dataForm.couponId !== 0"
        >
          <template #append>
            {{ $t('coupon.yuan') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="dataForm.couponType === 2"
        :label="$t('coupon.discountAmount')"
        prop="couponDiscount"
      >
        <el-input
          v-model="dataForm.couponDiscount"
          :placeholder="$t('coupon.discountAmount')"
          type="number"
          :disabled="dataForm.couponId !== 0"
        >
          <template #append>
            {{ $t('coupon.off') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('coupon.conditionsOfUse')"
        prop="cashCondition"
      >
        {{ $t('coupon.spendMoreThan') }}
        <el-input
          v-model="dataForm.cashCondition"
          :placeholder="$t('coupon.conditionsOfUse')"
          type="number"
          :disabled="dataForm.couponId !== 0"
        >
          <template #append>
            {{ $t('coupon.yuan') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('coupon.effectiveType')"
        np
        prop="validTimeType"
      >
        <el-radio-group
          v-model="dataForm.validTimeType"
          :disabled="dataForm.couponId !== 0"
        >
          <el-radio :label="1">
            {{ $t('coupon.fixedTime') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('coupon.effectiveAfterReceiving') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="dataForm.validTimeType === 1"
        :label="$t('coupon.startTime')"
        prop="startTime"
      >
        <el-date-picker
          v-model="dataForm.startTime"
          :disabled="dataForm.couponId !== 0"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetime"
          :placeholder="$t('coupon.chooseStartTime')"
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.validTimeType === 1"
        :label="$t('coupon.endTime')"
        prop="endTime"
      >
        <el-date-picker
          v-model="dataForm.endTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetime"
          :placeholder="$t('coupon.chooseEndTime')"
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.validTimeType === 2"
        :label="$t('coupon.AfterReceipt')"
        prop="afterReceiveDays"
      >
        <el-input
          v-model="dataForm.afterReceiveDays"
          type="number"
          :disabled="dataForm.couponId !== 0"
        >
          <template #append>
            {{ $t('coupon.day') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="dataForm.validTimeType === 2"
        :label="$t('coupon.validDate')"
        prop="validDays"
      >
        <el-input
          v-model="dataForm.validDays"
          type="number"
          :disabled="dataForm.couponId !== 0"
        >
          <template #append>
            {{ $t('coupon.day') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('coupon.restrictionsPerPerson')"
        prop="limitNum"
      >
        <el-input
          v-model="dataForm.limitNum"
          type="number"
        >
          <template #append>
            {{ $t('coupon.sheet') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('coupon.stock')"
        prop="stocks"
      >
        <el-input
          v-model="dataForm.stocks"
          type="number"
          :disabled="dataForm.couponId !== 0"
        >
          <template #append>
            {{ $t('coupon.sheet') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('coupon.applicableGoods')"
        prop="suitableProdType"
      >
        <el-radio-group v-model="dataForm.suitableProdType">
          <el-radio :label="0">
            {{ $t('coupon.allProductsParticipate') }}
          </el-radio>
          <el-radio :label="1">
            {{ $t('coupon.participateInDesignatedProd') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('coupon.specifiedProductsDoNotParticipate') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button
          v-if="dataForm.suitableProdType === 1 || dataForm.suitableProdType === 2"
          plain
          @click="prodsSelectHandle()"
        >
          {{ $t('coupon.selectGoods') }}
        </el-button>
      </el-form-item>
      <!-- 商品 -->
      <el-form-item v-if="dataForm.suitableProdType !== 0">
        <div class="prod-con">
          <el-card
            v-for="(couponProd, index) in dataForm.couponProds"
            :key="index"
            :body-style="{ padding: '0px' }"
            style="height: 160px;width: 120px"
          >
            <prod-pic
              height="104px"
              width="100%"
              :pic="couponProd.pic"
            />
            <div class="card-prod-bottom">
              <span class="card-prod-name">{{ couponProd.prodName }}</span>
              <el-button
                type="text"
                class="card-prod-name-button"
                @click="deleteProd(index)"
              >
                {{ $t('coupon.delete') }}
              </el-button>
            </div>
          </el-card>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">
          {{ $t('coupon.cancel') }}
        </el-button>
      </div>
    </template>
    <!-- 商品选择弹窗-->
    <prods-select
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      @refresh-select-prods="selectCouponProds"
    />
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataForm = ref({
  couponId: 0,
  couponName: '',
  subTitle: '',
  couponType: 1,
  reduceAmount: 0,
  couponDiscount: 0,
  cashCondition: 0,
  validTimeType: 1,
  launchTime: null,
  startTime: null,
  endTime: null,
  afterReceiveDays: 0,
  validDays: 0,
  stocks: 1,
  suitableProdType: 0,
  limitNum: 1,
  putonStatus: 0,
  couponProds: []
})
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const errorTip = ref(false)
const prodsSelectVisible = ref(false)
// eslint-disable-next-line no-unused-vars
const validate = (rule, value, callback) => {
  if (!/^[1-9]\d*$|^[1-9]\d*\.\d\d?$|^0\.\d\d?$/.test(value)) {
    callback(new Error($t('coupon.discountValidate')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateTime = (rule, value, callback) => {
  if (Date.parse(dataForm.value.startTime) >= Date.parse(dataForm.value.endTime)) {
    callback(new Error($t('coupon.validateTime')))
  } else {
    callback()
  }
}
const dataRule = {
  couponName: [
    { required: true, message: $t('coupon.couponNameCannotBeEmpty'), trigger: 'blur' }
  ],
  couponType: [
    { required: true, message: $t('coupon.couponTypeNotEmpty'), trigger: 'blur' }
  ],
  reduceAmount: [
    { required: true, message: $t('coupon.theDedEmpty'), trigger: 'blur' },
    { validator: validate, trigger: 'blur' }
  ],
  limitNum: [
    { required: true, message: $t('coupon.theLimitetBeEmpty'), trigger: 'blur' },
    { validator: validate, trigger: 'blur' }
  ],
  couponDiscount: [
    { required: true, message: $t('coupon.theDiscouBeEmpty'), trigger: 'blur' },
    { validator: validate, trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: $t('coupon.startTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: $t('coupon.endTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ],
  afterReceiveDays: [
    { required: true, message: $t('coupon.timeCannotBeEmpty'), trigger: 'blur' }
  ],
  validDays: [
    { required: true, message: $t('coupon.timeCannotBeEmpty'), trigger: 'blur' }
  ],
  cashCondition: [
    { required: true, message: $t('coupon.conditionBeEmpty'), trigger: 'blur' },
    { validator: validate, trigger: 'blur' }
  ],
  validTimeType: [
    { required: true, message: $t('coupon.effectiveotBeEmpty'), trigger: 'blur' }
  ],
  stocks: [
    { required: true, message: $t('coupon.invenEmpty'), trigger: 'blur' },
    { validator: validate, trigger: 'blur' }
  ],
  suitableProdType: [
    { required: true, message: $t('coupon.applicabltBeEmpty'), trigger: 'blur' }
  ]
}

watch(
  () => visible.value,
  () => {
    if (visible.value === false) {
      prodsSelectVisible.value = false
    }
  })

const dataFormRef = ref(null)
/**
 * 获取数据列表
 * @param couponId
 */
const init = (couponId) => {
  dataForm.value.couponId = couponId || 0
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
  if (dataForm.value.couponId) {
    getDataList()
  }
}
defineExpose({ init })

const getDataList = () => {
  http({
    url: http.adornUrl(`/platform/coupon/info/${dataForm.value.couponId}`),
    method: 'get',
    params: http.adornParams()
  })
    .then(({ data }) => {
      dataForm.value = data
    })
}

const prodsSelectRef = ref(null)
/**
 * 显示添加指定商品弹框
 */
const prodsSelectHandle = () => {
  prodsSelectVisible.value = true
  nextTick(() => {
    prodsSelectRef.value?.init(dataFormRef.value?.couponProds)
  })
}
/**
 * 删除指定商品
 * @param index
 */
const deleteProd = (index) => {
  dataForm.value.couponProds.splice(index, 1)
}
/**
 * 添加指定商品
 * @param prods
 */
const selectCouponProds = (prods) => {
  if (prods) {
    dataForm.value.couponProds = prods
  }
}
/**
 * 表单提交
 */
const onSubmit = () => {
  if (errorTip) {
    ElMessage({
      message: $t('coupon.quantitssThan0'),
      type: 'error',
      duration: 1500
    })
    return
  }
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      http({
        url: http.adornUrl('/platform/coupon'),
        method: dataForm.value.couponId ? 'put' : 'post',
        data: http.adornData({
          couponId: dataForm.value.couponId || undefined,
          couponName: dataForm.value.couponName,
          subTitle: dataForm.value.subTitle,
          couponType: dataForm.value.couponType,
          reduceAmount: dataForm.value.reduceAmount,
          couponDiscount: dataForm.value.couponDiscount,
          cashCondition: dataForm.value.cashCondition,
          validTimeType: dataForm.value.validTimeType,
          launchTime: dataForm.value.putonStatus === 0 ? dataForm.value.launchTime : null,
          startTime: dataForm.value.startTime,
          endTime: dataForm.value.endTime,
          afterReceiveDays: dataForm.value.afterReceiveDays,
          validDays: dataForm.value.validDays,
          stocks: dataForm.value.stocks,
          suitableProdType: dataForm.value.suitableProdType,
          limitNum: dataForm.value.limitNum,
          putonStatus: dataForm.value.putonStatus,
          couponProds: dataForm.value.couponProds
        })
      })
        .then(() => {
          ElMessage({
            message: $t('coupon.successfulOperation'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              dataForm.value.couponProds = []
              emit('refreshDataList', page)
              visible.value = false
            }
          })
        })
    }
  })
}
</script>

<style lang="scss" scoped>
.component-coupon-add-or-update {
  .prod-con {
    display: flex;
    flex-wrap: wrap;
    :deep(.el-card) {
      margin: 0 15px 15px 0;
    }
  }
}
</style>
